#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
//#include <usleep>
//
//#define N 3
//typedef void(*func_t)();
//
//func_t tasks[N]={NULL};
//void LoadTask()
//{
//
//}
//void HandlerTask()
//{
//
//}
//void DoOtherThing()
//{
//  HandlerTask();
//}
void ChildRun()
{
  //int *p=NULL;
  int cnt=5;
  while(cnt)
  {
    printf("i am chile process,pid:%d,ppid:%d,cnt:%d\n",getpid(),getppid(),cnt);
    sleep(1);
    cnt--;
   // *p=100;
  }
}
//自定义枚举常量
enum
{
  Success=0,
  Div_Zero,
  Mod_Zero,

};
const char* CodeErr(int code)
{
  switch(code)
  {
    case Success:
      return "Success";
    case Div_Zero:
      return "div zero";
    case Mod_Zero:
      return "mod zero";
    default:
      return "unknown";
  }
}
int exit_code = Success;

int Div(int x,int y)
{
  if(y==0)
  {
    exit_code=Div_Zero;
    return -1;
  }
  else
  {
    return x/y;
  }
}
int main()
{
  printf("i am father,pid:%d,ppid:%d\n",getpid(),getppid());
  pid_t id=fork();
  if(id==0)
  {
    //child
    ChildRun();
    printf("child quit ...\n");
    exit(123);
  }

  //father
  while(1)
  {
     int status=0;
     pid_t rid=waitpid(id,&status,WNOHANG);;//非阻塞等待
     if(rid==0)
     {
       usleep(1000);
       printf("child is running,father check next time\n");
//       DoOtherThing();
     }
     else if(rid>0)
     {
       if(WIFEXITED(status))
       {
         printf("child quit success,child exit code:%d\n",WEXITSTATUS(status));
       }
       else
       {
         printf("child quit unnormal!\n");
       }
       break;
     }
     else
     {
       printf("waitpid failed!\n");
       break;
     }
  }

  //sleep(7);
  ////father
  ////pid_t rid=wait(NULL);
  //int status =0;
  //pid_t rid=waitpid(id,&status,0);
  //if(rid>0)
  //{
  //  if(WIFEXITED(status))
  //  {
  //    printf("child quit success,child exit code:%d\n",WEXITSTATUS(status));
  //  }
  //  else
  //  {
  //    printf("child quit unnormal!\n");
  //  }
  //  printf("wait success,rid:%d\n",rid);
  //}
  //else
  //{
  //  printf("wait failed!\n");
  //}
  //sleep(3);
  //printf("father quit,status:%d,child quit code:%d,child quit signal:%d\n",status,(status>>8)&0xFF,status&0x7F);
//  int ret=Div(0,10);
//  printf("ret=%d [%s]\n",ret,CodeErr(exit_code));
//  ret=Div(10,0);
//  printf("ret=%d [%s]\n",ret,CodeErr(exit_code));
//  return exit_code;
//  for(int errcode=0;errcode<=255;errcode++)
//  {
//    printf("%d:%s\n",errcode,strerror(errcode));
//  }
//  printf("i am a process, pid:%d,ppid:%d\n",getpid(),getppid());
//  sleep(2);
//  return 100;
}
